"""
基础工具类定义
避免循环导入问题
"""

from abc import ABC, abstractmethod
from typing import Dict, List, Any, Optional
from dataclasses import dataclass
import re


@dataclass
class SearchResult:
    """搜索结果数据类"""
    title: str
    content: str
    url: str
    source: str  # docs, github, stackoverflow
    relevance_score: float
    metadata: Dict[str, Any] = None


class ExternalToolCache:
    """外部工具缓存"""
    
    def __init__(self):
        self._cache = {}
        self._max_size = 1000
    
    def _get_cache_key(self, tool: str, query: str) -> str:
        """生成缓存键"""
        return f"{tool}:{hash(query.lower().strip())}"
    
    def get(self, tool: str, query: str) -> Optional[List[SearchResult]]:
        """获取缓存结果"""
        key = self._get_cache_key(tool, query)
        if key in self._cache:
            print(f"🎯 [缓存] 命中缓存: {tool} - {query[:30]}...")
            return self._cache[key]
        return None
    
    def set(self, tool: str, query: str, results: List[SearchResult]):
        """设置缓存结果"""
        key = self._get_cache_key(tool, query)
        if len(self._cache) >= self._max_size:
            # 简单的LRU：删除第一个元素
            first_key = next(iter(self._cache))
            del self._cache[first_key]
        self._cache[key] = results
        print(f"💾 [缓存] 保存缓存: {tool} - {len(results)}条结果")


class BaseExternalTool(ABC):
    """外部工具基类"""
    
    def __init__(self, cache: ExternalToolCache):
        self.cache = cache
        # 设置默认值，避免属性错误
        self.timeout = 30  # 默认超时时间
        self.max_results = 10  # 默认最大结果数
    
    @abstractmethod
    async def search(self, query: str) -> List[SearchResult]:
        """搜索方法，子类必须实现"""
        pass
    
    def _clean_text(self, text: str) -> str:
        """清理文本"""
        if not text:
            return ""
        # 移除多余的空白字符
        text = re.sub(r'\s+', ' ', text)
        # 移除特殊字符
        text = re.sub(r'[^\w\s\-\.\,\!\?\:\;]', '', text)
        return text.strip()